<script setup lang="ts">
import {computed, defineProps, useAttrs, useSlots} from 'vue';
import {devSelectMutexProps} from './selectMutex';
import {devDeepMerge, useConfig} from "@/index";
import {ElOption, ElSelect} from "element-plus";

const attrs = useAttrs();
const slots = useSlots();
const props = defineProps(devSelectMutexProps);
const config = useConfig();

// 合并配置和属性，避免每次渲染重新计算
const mergedProps = computed(() => devDeepMerge(config.elSelectProps, attrs));

// 计算禁用状态
const computeDisabled = (item: any) => {
  if (item[props.optionDisabledKey]) return true;
  const isSelected = attrs.multiple
      ? Array.isArray(attrs.modelValue) && attrs.modelValue.includes(item[props.optionValueKey])
      : attrs.modelValue === item[props.optionValueKey];
  return !isSelected && props.allSelectValue.includes(item[props.optionValueKey]);
};

// 使用computed生成带禁用状态的选项，自动追踪依赖
const optionsWithDisabled = computed(() =>
    (props.options || []).map(item => ({
      ...item,
      disabled: computeDisabled(item)
    }))
);


defineOptions({ name: 'DevSelectMutex' });
</script>

<template>
  <el-select v-bind="mergedProps">
    <el-option
        v-for="item in optionsWithDisabled"
        v-bind="attrs?.props || {}"
        :key="item[props.optionValueKey]"
        :value="item[props.optionValueKey]"
        :label="item[props.optionLabelKey]"
        :disabled="item.disabled"
    />
    <template v-for="(_, slotName) in slots" #[slotName]="scope">
      <slot :name="slotName" v-bind="scope" />
    </template>
  </el-select>
</template>
